package com.mk.episodecalendar.security;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class AuthModule {
	private String AUTH_URL_FORMAT = "http://episodecalendar.com/android/auth/%s/%s";
	
	public AuthResult Login(String userName, String password)
	{
		URLConnection urlCon = null;
		try
		{
			URL url = new URL(String.format(AUTH_URL_FORMAT, URLEncoder.encode(userName), URLEncoder.encode(password)));
			urlCon = url.openConnection();
		}
		catch (Exception e)
		{
			return new AuthResult(false);
		}
		
		try
		{
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = db.parse(urlCon.getInputStream());
			String result = doc.getElementsByTagName("result").item(0).getFirstChild().getNodeValue();
			Boolean boolResult = result.equals("true");
			String authKey = "";
			if(boolResult)
			{
				authKey = doc.getElementsByTagName("auth_key").item(0).getFirstChild().getNodeValue();
			}
			
			return new AuthResult(boolResult, authKey);
		}
		catch (Exception e) 
		{
			return new AuthResult(false);
		}
	}
}
